import Vue from 'vue'
import router from './router'
import store from './store'
import { Message } from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { getToken } from '@/utils/auth' // get token from cookie
import getPageTitle from '@/utils/get-page-title'
import { constantRoutes } from '@/router'

NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['/login'] // no redirect whitelist

router.beforeEach(async(to, from, next) => {
  if (to.name) await store.dispatch('app/togglePagesName', to.name) // 性能监控
  clearHttpRequestingList()
  // 开始进度条
  NProgress.start()

  // 设置页面标题
  document.title = getPageTitle(to.meta.title)

  // 判断用户是否已经登录
  const hasToken = getToken()

  if (hasToken) {
    if (to.path === '/login') {
      console.log('如果已登录，则重定向到主页')
      // if is logged in, redirect to the home page
      next({ path: '/' })
      NProgress.done()
    } else {
      const hasGetUserInfo = store.getters.name
      if (hasGetUserInfo) {
        next()
      } else {
        try {
          await store.dispatch('user/toggleMenusList', constantRoutes) // 解决刷新加载前出现无权限
          // get user info
          await store.dispatch('user/getInfo')
          console.log('登录成功 同步方法获取侧边栏菜单')
          let permissions = []
          // 登录成功 同步方法获取侧边栏菜单
          const url = process.env.NODE_ENV === 'development' ? require('@/settings.js').developmentApi + `/api/admin/menus` : `/api/admin/menus`
          console.log('xhr 请求地址', url)
          const xhr = new XMLHttpRequest()
          const formData = new FormData()
          xhr.open('get', url, false)
          // console.log('store.getters.acadyearterm', store.getters.acadyearterm)
          // if (store.getters.acadyearterm) {
          //   if (store.getters.acadyearterm.current?.acad_year_term) {
          //     xhr.setRequestHeader('Acad-Year-Term', store.getters.acadyearterm.current?.acad_year_term)
          //   }
          // }
          xhr.setRequestHeader('Authorization', hasToken)
          xhr.setRequestHeader('Accept', 'application/json')
          xhr.setRequestHeader('Content-Type', 'application/json')
          xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest')
          xhr.onload = (e) => {
            console.log('xhr.onload--------', e)
            const data = JSON.parse(e.currentTarget.response)
            if (data.code === 0 && data.data) {
              data.data.forEach((item) => {
                if (!item.children.length) {
                  item.children.push({
                    name: 'index',
                    title: item.title
                  })
                }
              })
              permissions = data.data
            }
          }
          xhr.send(formData)
          const accessRoutes = await store.dispatch('permission/generateRoutes', permissions)
          console.log('accessRoutes', accessRoutes)
          router.addRoutes(accessRoutes)
          const routesGather = getRoutes(permissions, false, [])
          await store.dispatch('user/toggleMenusList', permissions)
          if (routesGather.includes(to.path)) { // 解决切换身份或切换学年学期时导致重定向路由不存在出现空白页
            console.log('检查到路由存在', to)
            next({ ...to, replace: true })
          } else if (permissions.length) {
            console.log('检查到路由不存在', permissions[0].redirect)
            next({ path: permissions[0].redirect, replace: true })
          } else {
            next({ path: 'dashboard/index/index', replace: true })
          }
        } catch (error) {
          console.log('删除令牌并转到登录页面重新登录', error)
          // 删除令牌并转到登录页面重新登录
          await store.dispatch('user/resetToken')
          Message.error(error || 'Has Error')
          next(`/login?redirect=${to.path}`)
          NProgress.done()
        }
      }
    }
  } else {
    /* 没有令牌*/
    if (whiteList.indexOf(to.path) !== -1) {
      console.log('在免费登录白名单，直接去')
      // 在免费登录白名单，直接去
      next()
    } else {
      console.log('其他没有访问权限的页面被重定向到登录页面。')
      // 其他没有访问权限的页面被重定向到登录页面。
      next(`/login?redirect=${to.path}`)
      NProgress.done()
    }
    await store.dispatch('user/toggleMenusList', constantRoutes) // 解决未登录时登录页面出现无权限
  }
})

router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})

// 动态路由自动生成path
// function firstToUpper(str) { // 首字母转大写
//   return str.replace(/( |^)[a-z]/g, (L) => L.toUpperCase())
// }
function firstLower(str) { // 首字母转小写
  return str.replace(/^./, (L) => L.toLowerCase())
}
function getRoutes(data, itemName, pathList) {
  data?.forEach((item) => {
    // eslint-disable-next-line no-prototype-builtins

    // const path = itemName ? '/' + firstLower(itemName) + '/' + firstLower(item.page_name) : '/' + firstLower(item.page_name)
    // pathList.push(path)

    // item.children && item.children.length > 0 ? getRoutes(item.children, item.page_name, pathList) : delete item.children

    const path = itemName ? '/' + firstLower(itemName) + '/' + firstLower(item.name) : '/' + firstLower(item.name)
    pathList.push(path)

    item.children && item.children.length > 0 ? getRoutes(item.children, item.name, pathList) : delete item.children
  })

  // console.log('菜单', pathList)

  return pathList
}

// 动态路由本地与服务器约定生成path
// import { SunRouterPath } from '@/router/path'
// function getRoutes(data, itemName, pathList) {
//   data?.forEach((item) => {
//     // eslint-disable-next-line no-prototype-builtins
//     if (itemName && item.hasOwnProperty('evaluation_status')) {
//       pathList.push(SunRouterPath[itemName] + '/' + SunRouterPath[itemName + '.' + item.name] + '/' + item.evaluation_status)
//     } else {
//       pathList.push(itemName ? SunRouterPath[itemName] + '/' + SunRouterPath[itemName + '.' + item.name] : SunRouterPath[item.name])
//     }
//     item.children && item.children.length > 0 ? getRoutes(item.children, item.name, pathList) : delete item.children
//   })
//   return pathList
// }

// 清空cancelToken中的cancel函数
function clearHttpRequestingList() {
  // 路由切换检测是否强行中断， 强行中断时才向下执行
  console.log('路由切换检测是否强行中断， 强行中断时才向下执行', Vue.$httpRequestList)
  if (Vue.$httpRequestList.length > 0) {
    Vue.$httpRequestList.forEach((item) => {
      // 给个标志，中断请求
      item('interrupt')
    })
    Vue.$httpRequestList = []
  }
}
